package com.rightsidetech.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.PageRequest;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.base.TimeQueryRequest;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.enums.SystemParamsEnum;
import com.rightsidetech.system.dtos.request.*;
import com.rightsidetech.system.dtos.request.store.StoreStockReq;
import com.rightsidetech.system.dtos.request.store.SysAgentStorkPageReq;
import com.rightsidetech.system.dtos.request.store.SysAgentStorkReplenishReq;
import com.rightsidetech.system.dtos.response.*;
import com.rightsidetech.system.dtos.response.store.*;
import com.rightsidetech.system.entity.*;
import com.rightsidetech.system.entity.store.SysStoreInfo;
import com.rightsidetech.system.entity.store.SysStoreLoginInfo;
import com.rightsidetech.system.mapper.*;
import com.rightsidetech.system.service.SysStoreStorkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author: yhr
 * @Date: 2021-12-09 15:47
 */
@Slf4j
@Service("sysStoreStorkServiceImpl")
public class SysStoreStorkServiceImpl implements SysStoreStorkService {
    @Resource
    private SysStoreStockMapper sysStoreStockMapper;
    @Resource
    private SysStoreReplenishMapper sysStoreReplenishMapper;
    @Resource
    private SysStoreReplenishDetailsMapper sysStoreReplenishDetailsMapper;
    @Resource
    private SysStoreLoginInfoMapper sysStoreLoginInfoMapper;
    @Resource
    private SysSystemParamMapper sysSystemParamMapper;
    @Resource
    private SysAgentLoginInfoMapper sysAgentLoginInfoMapper;
    @Resource
    private SysStoreInfoMapper sysStoreInfoMapper;

    @Override
    public ResponseData<PageInfo<SysStoreStorkPageResp>> page(SysStoreStorkPageReq req) {
        SysSystemParam systemParam = sysSystemParamMapper.selectValueByKey(SystemParamsEnum.ALERT_CARGO.getValue());
        if (ObjectUtils.isEmpty(systemParam)){
            return ResponseData.fail("系统配置失效");
        }
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        req.setWarn(Long.valueOf(systemParam.getParamValue()));
        List<SysStoreStorkPageResp> page = sysStoreStockMapper.page(req);
        return ResponseData.success(new PageInfo<>(page));
    }

    @Override
    public ResponseData<PageInfo<SysStoreStorkInfoResp>> selectReplenishInfo(SysStoreIdReq req) {
        SysSystemParam systemParam = sysSystemParamMapper.selectValueByKey(SystemParamsEnum.ALERT_CARGO.getValue());
        if (ObjectUtils.isEmpty(systemParam)){
            return ResponseData.fail("系统配置失效");
        }
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        req.setWarn(Long.valueOf(systemParam.getParamValue()));
        List<SysStoreStorkInfoResp> resps = sysStoreStockMapper.selectReplenishInfo(req);
        return ResponseData.success(new PageInfo<>(resps));
    }

    @Override
    public ResponseData<PageInfo<SysStoreStorkReplenishResp>> replenishPage(SysStoreStorkReplenishReq req) {
        List<SysStoreStorkReplenishResp> resps = new ArrayList<>();

        if (!StringUtils.isEmpty(req.getCommodityName()) || !StringUtils.isEmpty(req.getCommoditySpecs())){
            List<Long> details = sysStoreReplenishDetailsMapper.selectByReplenishId(req);
            if (CollectionUtils.isEmpty(details)){
                return ResponseData.success(new PageInfo<>(null));
            }
            PageHelper.startPage(req.getPageNo(), req.getPageSize());
            if(details.isEmpty()){
                details = new ArrayList<>();
                details.add(0L);
            }
            resps  = sysStoreReplenishMapper.selectReplenishOneByList(req,details);
        }else {
            PageHelper.startPage(req.getPageNo(), req.getPageSize());
            resps  = sysStoreReplenishMapper.selectReplenish(req);
        }
        return ResponseData.success(new PageInfo<>(resps));

    }

    @Override
    public ResponseData<PageInfo<SysStoreStorkReplenishInfoResp>> replenishInfo(SysStoreStorkReplenishInfoReq req) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<SysStoreStorkReplenishInfoResp> resps = sysStoreReplenishDetailsMapper.selectByReplenish(req);
        return ResponseData.success(new PageInfo<>(resps));
    }

    @Override
    public ResponseData<PageInfo<SysStoreStorkReplenishInfoResp>> replenishAgentInfo(SysStoreStorkReplenishInfoReq req, Long loginInfoId) {
        SysAgentLoginInfo loginInfo = sysAgentLoginInfoMapper.selectByPrimaryKey(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        List<SysStoreStorkReplenishInfoResp> resps = sysStoreReplenishDetailsMapper.selectAgentByReplenish(req,loginInfo.getAgentInfoId());
        return ResponseData.success(new PageInfo<>(resps));
    }

    @Override
    public ResponseData<PageInfo<SysStoreStorkAppResp>> listAll(PageRequest req, Long loginInfoId) {
        SysStoreLoginInfo storeLoginInfo = sysStoreLoginInfoMapper.selectByStoreInfoId(loginInfoId);
        if (ObjectUtils.isEmpty(storeLoginInfo)){
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }

//        SysSystemParam systemParam = sysSystemParamMapper.selectValueByKey(SystemParamsEnum.ALERT_CARGO.getValue());
//        if (ObjectUtils.isEmpty(systemParam)){
//            return ResponseData.fail("系统配置失效");
//        }
        PageHelper.startPage(req.getPageNo(),req.getPageSize());
        List<SysStoreStorkAppResp> list = sysStoreStockMapper.listAll(storeLoginInfo.getStoreId());
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public ResponseData listReplenish(Long loginInfoId, Byte verify, TimeQueryRequest timeQueryRequest) {
        SysStoreLoginInfo storeLoginInfo = sysStoreLoginInfoMapper.selectByStoreId(loginInfoId);
        if (ObjectUtils.isEmpty(storeLoginInfo)){
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        PageHelper.startPage(timeQueryRequest.getPageNo(), timeQueryRequest.getPageSize());
        List<SysStoreStorkReplenishAppResp> appResps = sysStoreReplenishMapper.selectReplenishApp(storeLoginInfo.getStoreId(),verify,timeQueryRequest);
        for (SysStoreStorkReplenishAppResp appResp:appResps){
            if (appResp.getType()==(byte)1){
                appResp.setName("过期换货单");
            }
        }
        if (ObjectUtils.isEmpty(appResps)){
            return ResponseData.success();
        }
        return ResponseData.success(new PageInfo(appResps));
    }

    @Override
    public ResponseData<List<SysStoreStorkDetailsAppResp>> listReplenishInfo(Long id) {
        return ResponseData.success(sysStoreReplenishDetailsMapper.selectReplenishInfo(id));
    }

    @Override
    public ResponseData<List<HomeStoreStorkResp>> outofStockStore(Long agentInfoId) {
        SysSystemParam systemParam = sysSystemParamMapper.selectValueByKey(SystemParamsEnum.ALERT_CARGO.getValue());
        if (ObjectUtils.isEmpty(systemParam)){
            return ResponseData.fail("库存预警值失效");
        }
        Long warnNumber =  Long.parseLong(systemParam.getParamValue());
        if (StringUtils.isEmpty(warnNumber) || warnNumber <= 0){
            if (ObjectUtils.isEmpty(systemParam)){
                return ResponseData.fail("未设置库存预警值");
            }
        }
//        //查询代理商下所有门店
//        List<StoreResp> storeRespList = sysStoreInfoMapper.findByAgentInfoId(agentInfoId, null, (byte) 1);
//        if (CollectionUtils.isEmpty(storeRespList)){
//            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
//        }
        //查询代理商下门店库存
        List<HomeStoreStorkResp> list = sysStoreStockMapper.selectOutofStockByAgentId(agentInfoId,warnNumber);
//        for (HomeStoreStorkResp storeStorkResp : list){
//            for (StoreResp storeResp : storeRespList){
//                if (storeResp.getId().equals(storeStorkResp.getStoreId())){
//                    storeStorkResp.setStoreName(storeResp.getStoreName());
//                }
//            }
//        }
        return ResponseData.success(list);
    }

    @Override
    public ResponseData updateVerifyById(Long id) {
        SysStoreReplenish sysStoreReplenish = sysStoreReplenishMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(sysStoreReplenish)){
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        if (sysStoreReplenish.getIsVerify() == 1){
            return ResponseData.fail("该记录已被确认");
        }

        List<SysStoreReplenishDetails> details = sysStoreReplenishDetailsMapper.selectAllByReplenishIdSysStoreReplenishDetails(id);

        if (sysStoreReplenish.getType() == 1){
            for (SysStoreReplenishDetails detail : details){
                SysStoreStock sysStoreStock = sysStoreStockMapper.selectBySpecsId(sysStoreReplenish.getStoreId(), detail.getCommoditySpecsId());
                if (!ObjectUtils.isEmpty(sysStoreStock)) {
                    Long expiredNum = sysStoreStock.getExpiredNum() - detail.getNum();
                    sysStoreStockMapper.updateStorkExpiredNum(sysStoreStock.getStoreId(), detail.getCommoditySpecsId(), expiredNum);
                }
                //修改最早一批次的库存详细
                List<Long> ids = sysStoreReplenishMapper.selectByStoreId(sysStoreReplenish.getStoreId());
                if (!ObjectUtils.isEmpty(ids)){
                    recursion(ids, detail.getCommodityId(), detail.getCommoditySpecsId(), detail.getNum());
                }
            }
        }
        if (sysStoreReplenish.getType() == 0) {
            for (SysStoreReplenishDetails detail : details) {
                SysStoreStock sysStoreStock = sysStoreStockMapper.selectBySpecsId(sysStoreReplenish.getStoreId(), detail.getCommoditySpecsId());
                if (!ObjectUtils.isEmpty(sysStoreStock)) {
                    Long sum = sysStoreStock.getNum() + detail.getNum();
                    sysStoreStockMapper.updateStorkNum(sysStoreStock.getStoreId(), detail.getCommoditySpecsId(), sum);
                } else {
                    //库存新增
                    SysStoreStock stock = new SysStoreStock();
                    stock.setStoreId(sysStoreReplenish.getStoreId());
                    stock.setCommodityId(detail.getCommodityId());
                    stock.setCommoditySpecsId(detail.getCommoditySpecsId());
                    stock.setCommodityName(detail.getCommodityName());
                    stock.setTypeName(detail.getTypeName());
                    stock.setBrandName(detail.getBrandName());
                    stock.setCommoditySpecs(StringUtils.isEmpty(detail.getCommoditySpecs()) ? null : detail.getCommoditySpecs());
                    stock.setNum(detail.getNum());
                    stock.setCreatedAt(new Date());
                    sysStoreStockMapper.insertSelective(stock);
                }
                // todo 2022-3-21 18:24:42 如果库存是负的 同时调整补货记录的剩余数量
                if (sysStoreStock.getNum() < 0) {
                    //修改最早一批次的库存详细
                    List<Long> ids = sysStoreReplenishMapper.selectByStoreId(sysStoreReplenish.getStoreId());
                    if (!ObjectUtils.isEmpty(ids)) {
                        recursion(ids, detail.getCommodityId(), detail.getCommoditySpecsId(), -sysStoreStock.getNum());
                    }
                }
            }
        }

        return ResponseData.success(sysStoreReplenishMapper.updateVerifyById(id));
    }

    @Override
    public ResponseData checkVerifyById(Long id) {
        SysStoreReplenish sysStoreReplenish = sysStoreReplenishMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(sysStoreReplenish)){
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        if (sysStoreReplenish.getIsVerify() == 1){
            return ResponseData.fail("存在记录已被确认");
        }
        return ResponseData.success();
    }

    @Override
    public void updateVerifyHavedCheckedById(Long id) {
        SysStoreReplenish sysStoreReplenish = sysStoreReplenishMapper.selectByPrimaryKey(id);
        List<SysStoreReplenishDetails> details = sysStoreReplenishDetailsMapper.selectAllByReplenishIdSysStoreReplenishDetails(id);

        if (sysStoreReplenish.getType() == 1){
            for (SysStoreReplenishDetails detail : details){
                SysStoreStock sysStoreStock = sysStoreStockMapper.selectBySpecsId(sysStoreReplenish.getStoreId(), detail.getCommoditySpecsId());
                if (!ObjectUtils.isEmpty(sysStoreStock)) {
                    Long expiredNum = sysStoreStock.getExpiredNum() - detail.getNum();
                    sysStoreStockMapper.updateStorkExpiredNum(sysStoreStock.getStoreId(), detail.getCommoditySpecsId(), expiredNum);
                }
                //修改最早一批次的库存详细
                List<Long> ids = sysStoreReplenishMapper.selectByStoreId(sysStoreReplenish.getStoreId());
                if (!ObjectUtils.isEmpty(ids)){
                    recursion(ids, detail.getCommodityId(), detail.getCommoditySpecsId(), detail.getNum());
                }
            }
        }

        if (sysStoreReplenish.getType() == 0) {
            for (SysStoreReplenishDetails detail : details) {
                SysStoreStock sysStoreStock = sysStoreStockMapper.selectBySpecsId(sysStoreReplenish.getStoreId(), detail.getCommoditySpecsId());
                if (!ObjectUtils.isEmpty(sysStoreStock)) {
                    Long sum = sysStoreStock.getNum() + detail.getNum();
                    sysStoreStockMapper.updateStorkNum(sysStoreStock.getStoreId(), detail.getCommoditySpecsId(), sum);
                } else {
                    //库存新增
                    SysStoreStock stock = new SysStoreStock();
                    stock.setStoreId(sysStoreReplenish.getStoreId());
                    stock.setCommodityId(detail.getCommodityId());
                    stock.setCommoditySpecsId(detail.getCommoditySpecsId());
                    stock.setCommodityName(detail.getCommodityName());
                    stock.setTypeName(detail.getTypeName());
                    stock.setBrandName(detail.getBrandName());
                    stock.setCommoditySpecs(StringUtils.isEmpty(detail.getCommoditySpecs()) ? null : detail.getCommoditySpecs());
                    stock.setNum(detail.getNum());
                    stock.setCreatedAt(new Date());
                    sysStoreStockMapper.insertSelective(stock);
                }
                // todo 2022-3-21 18:24:42 如果库存是负的 同时调整补货记录的剩余数量
                if (sysStoreStock.getNum() < 0) {
                    //修改最早一批次的库存详细
                    List<Long> ids = sysStoreReplenishMapper.selectByStoreId(sysStoreReplenish.getStoreId());
                    if (!ObjectUtils.isEmpty(ids)) {
                        recursion(ids, detail.getCommodityId(), detail.getCommoditySpecsId(), -sysStoreStock.getNum());
                    }
                }
            }
        }

        sysStoreReplenishMapper.updateVerifyById(id);
    }

    @Override
    public ResponseData<SysVerifyReplenishResp> verifyReplenish(Long loginInfoId) {
        SysStoreLoginInfo storeLoginInfo = sysStoreLoginInfoMapper.selectByStoreInfoId(loginInfoId);
        if (ObjectUtils.isEmpty(storeLoginInfo)){
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        Long num = sysStoreReplenishMapper.selectCountVerify(storeLoginInfo.getStoreId());
        SysVerifyReplenishResp resp = new SysVerifyReplenishResp();
        resp.setNum(num);
        return ResponseData.success(resp);
    }

    @Override
    public ResponseData<PageInfo<SysAgentStorkPageResp>> pageAgent(SysAgentStorkPageReq req, Long loginInfoId) {
        SysAgentLoginInfo loginInfo = sysAgentLoginInfoMapper.selectByPrimaryKey(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
//        SysSystemParam systemParam = sysSystemParamMapper.selectValueByKey(SystemParamsEnum.ALERT_CARGO.getValue());
//        if (ObjectUtils.isEmpty(systemParam)){
//            return ResponseData.fail("系统配置失效");
//        }
//        req.setWarn(Long.valueOf(systemParam.getParamValue()));
        List<SysAgentStorkPageResp> page = sysStoreStockMapper.pageAgent(req,loginInfo.getAgentInfoId());
        return ResponseData.success(new PageInfo<>(page));
    }

    @Override
    public ResponseData<PageInfo<SysStoreStorkInfoResp>> selectAgentReplenishInfo(SysStoreIdReq req, Long loginInfoId) {
        SysAgentLoginInfo loginInfo = sysAgentLoginInfoMapper.selectByPrimaryKey(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        SysSystemParam systemParam = sysSystemParamMapper.selectValueByKey(SystemParamsEnum.ALERT_CARGO.getValue());
        if (ObjectUtils.isEmpty(systemParam)){
            return ResponseData.fail("系统配置失效");
        }
        req.setWarn(Long.valueOf(systemParam.getParamValue()));
        List<SysStoreStorkInfoResp> resps = sysStoreStockMapper.selectAgentReplenishInfo(req,loginInfo.getAgentInfoId());
        return ResponseData.success(new PageInfo<>(resps));
    }

    @Override
    public ResponseData<PageInfo<SysAgentStorkReplenishResp>> replenishAgentPage(SysAgentStorkReplenishReq req, Long loginInfoId) {
        SysAgentLoginInfo loginInfo = sysAgentLoginInfoMapper.selectByPrimaryKey(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        List<SysAgentStorkReplenishResp> resps = new ArrayList<>();
        if (!StringUtils.isEmpty(req.getCommodityName()) || !StringUtils.isEmpty(req.getCommoditySpecs())){
            List<Long> details = sysStoreReplenishDetailsMapper.selectAgentByReplenishId(req);
            PageHelper.startPage(req.getPageNo(), req.getPageSize());
            if(details.isEmpty()){
                details = new ArrayList<>();
                details.add(0L);
            }
            resps  = sysStoreReplenishMapper.selectAgentReplenishOne(req,loginInfo.getAgentInfoId(), details);
        }else {
            PageHelper.startPage(req.getPageNo(), req.getPageSize());
            resps  = sysStoreReplenishMapper.selectAgentReplenish(req,loginInfo.getAgentInfoId());
        }
        return ResponseData.success(new PageInfo<>(resps));

    }

    @Override
    public ResponseData<PageInfo<SysStoreStorkAppResp>> listAgentAll(StoreStockReq req, Long agentInfoId) {
        int store = sysStoreStockMapper.selectByStoreId(req.getStoreId());
        if (agentInfoId!=store){
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
//        SysSystemParam systemParam = sysSystemParamMapper.selectValueByKey(SystemParamsEnum.ALERT_CARGO.getValue());
//        if (ObjectUtils.isEmpty(systemParam)){
//            return ResponseData.fail("系统配置失效");
//        }
        PageHelper.startPage(req.getPageNo(),req.getPageSize());
        List<SysStoreStorkAppResp> list = sysStoreStockMapper.listAll(req.getStoreId());
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public ResponseData listReplenishAgent(Long agentInfoId, TimeQueryRequest timeQueryRequest){
        PageHelper.startPage(timeQueryRequest.getPageNo(), timeQueryRequest.getPageSize());
        List<SysAgentStorkReplenishListResp> appResps = sysStoreReplenishMapper.selectReplenishAgent(agentInfoId,timeQueryRequest);
        if (ObjectUtils.isEmpty(appResps)){
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        return ResponseData.success(new PageInfo(appResps));
    }

    public List<SysAgentStorkStoreResp> ridRepeat(List<SysAgentStorkStoreResp> list) {
        List<SysAgentStorkStoreResp> listNew = new ArrayList<>();
        Set set = new HashSet();
        for (SysAgentStorkStoreResp str : list) {
            if (set.add(str.getReplenishTime())) {
                listNew.add(str);
            }
        }
        return listNew;
    }

    @Override
    public ResponseData saveStork(AgentAppStoreStorkReq req, Long agentLoginId, Long num) {
        AgentRegionResp regionResp = sysAgentLoginInfoMapper.selectLoginName(agentLoginId);
        SysStoreReplenish replenish = new SysStoreReplenish();
        if (!ObjectUtils.isEmpty(regionResp)){
            SysStoreInfo sysStoreInfo = sysStoreInfoMapper.selectByPrimaryKey(req.getStoreId());
            if (!ObjectUtils.isEmpty(sysStoreInfo) && num > 0){
                replenish.setStoreId(req.getStoreId());
                replenish.setStoreName(sysStoreInfo.getStoreName());
                replenish.setReplenisherId(agentLoginId);
                replenish.setReplenisherLoginName(regionResp.getLoginName());
                replenish.setAgentInfoId(regionResp.getAgentId());
                replenish.setAreaId(regionResp.getAreaId());
                replenish.setReplenishNum(num);
                replenish.setReplenishTime(new Date());
                replenish.setCreatedAt(new Date());
                sysStoreReplenishMapper.insertSelective(replenish);
            }
        }
        return ResponseData.success(replenish.getId());
    }

    @Override
    public ResponseData saveAfterStork(AgentAppStoreStorkReq req, Long agentLoginId, Long num) {
        AgentRegionResp regionResp = sysAgentLoginInfoMapper.selectLoginName(agentLoginId);
        SysStoreReplenish replenish = new SysStoreReplenish();
        if (!ObjectUtils.isEmpty(regionResp)){
            SysStoreInfo sysStoreInfo = sysStoreInfoMapper.selectByPrimaryKey(req.getStoreId());
            if (!ObjectUtils.isEmpty(sysStoreInfo) && num > 0){
                replenish.setStoreId(req.getStoreId());
                replenish.setStoreName(sysStoreInfo.getStoreName());
                replenish.setReplenisherId(agentLoginId);
                replenish.setReplenisherLoginName(regionResp.getLoginName());
                replenish.setAgentInfoId(regionResp.getAgentId());
                replenish.setAreaId(regionResp.getAreaId());
                replenish.setReplenishNum(num);
                replenish.setReplenishTime(new Date());
                replenish.setCreatedAt(new Date());
                replenish.setType((byte) 1);
                sysStoreReplenishMapper.insertSelective(replenish);
            }
        }
        return ResponseData.success(replenish.getId());
    }

    @Override
    public ResponseData updateNum(Long replenishId,Long num) {
        return ResponseData.success(sysStoreReplenishMapper.updateNum(replenishId,num));
    }

    @Override
    public int updateStorkNum(Long storeId, Long specsId, Long num) {
        return sysStoreStockMapper.updateStorkNum(storeId,specsId,num);
    }

    @Override
    public AgentRegionResp selectLoginName(Long loginId) {
        return sysAgentLoginInfoMapper.selectLoginName(loginId);
    }

    @Override
    public int insertSelective(SysStoreReplenishDetails req) {
        return sysStoreReplenishDetailsMapper.insertSelective(req);
    }

    @Override
    public int insertStockSelective(SysStoreStock req) {
        return sysStoreStockMapper.insertSelective(req);
    }

    @Override
    public ResponseData<List<StoreStorkResp>> storeStorkPage(StoreStorkSearchReq req, Long agentInfoId) {

        List<StoreStorkResp> list = sysStoreStockMapper.findByStorkAgentInfoId(agentInfoId, req.getStoreName());
        return ResponseData.success(list);
    }

    @Override
    public ResponseData<List<StoreStorkExceedResp>> storeStorkExceed(Long agentInfoId) {
        SysSystemParam systemParam = sysSystemParamMapper.selectValueByKey(SystemParamsEnum.BATTERY_TIME_OUT.getValue());
        if (ObjectUtils.isEmpty(systemParam)){
            return ResponseData.fail("系统配置失效");
        }

        return ResponseData.success(sysStoreReplenishDetailsMapper.selectTimeOut(agentInfoId,systemParam.getParamValue()));
    }

    @Override
    public SysStoreStock selectCountStock(Long storeId, Long specsId) {
        return sysStoreStockMapper.selectBySpecsId(storeId,specsId);
    }
    @Override
    public SysStoreStock selectNoneSpecsStock(Long storeId, Long commodityId) {
        return sysStoreStockMapper.selectNoneSpecsByCommodityId(storeId,commodityId);
    }


    @Override
    public ResponseData outStork(Long storeId, Long specsId, Long commodityId, Long num) {
        SysStoreStock stock = sysStoreStockMapper.selectBySecsComm(storeId, specsId, commodityId);

        if (ObjectUtils.isEmpty(stock)){
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        Long countNum = stock.getNum()-num;
        long expiredNum = stock.getExpiredNum() - num;
        expiredNum = expiredNum <= 0 ? 0 : expiredNum;
        sysStoreStockMapper.updateStorkNumBySpecsId(storeId,specsId,commodityId,countNum,expiredNum);

        //修改最早一批次的库存详细
        List<Long> ids = sysStoreReplenishMapper.selectByStoreId(storeId);
        if (!ObjectUtils.isEmpty(ids)){
            boolean recursion = recursion(ids, commodityId, specsId, num);
            if (!recursion){
                return ResponseData.fail("该商品库存不足");
            }
        }
        return ResponseData.success();
    }

    private boolean recursion(List<Long> ids,Long commodityId,Long specsId,Long num){
        SysStoreReplenishDetails details = sysStoreReplenishDetailsMapper.selectLimit(ids,commodityId,specsId);
        if (ObjectUtils.isEmpty(details)){
            return false;
        }
        long detNum = details.getHaveStock() - num;
        if (detNum >= 0){
            sysStoreReplenishDetailsMapper.updateNum(details.getId(),detNum);
            return true;
        }else {
            sysStoreReplenishDetailsMapper.updateNum(details.getId(),0L);
            recursion(ids,commodityId,specsId,-detNum);
        }
        return true;
    }

    @Override
    public ResponseData retreatStork(Long storeId, Long specsId, Long commodityId, Long num) {
        SysStoreStock stock = sysStoreStockMapper.selectBySecsComm(storeId, specsId, commodityId);
        if (ObjectUtils.isEmpty(stock)){
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }

        //修改最早一批次的库存详细
        List<Long> ids = sysStoreReplenishMapper.selectByStoreId(storeId);
        //回退 过期数量
        Long retreatNum = 0L;
        if (!ObjectUtils.isEmpty(ids)){
            //todo  判断回退了哪些补货记录 2022-3-23 14:16:34
            List<SysStoreReplenishDetails> detailsList = new ArrayList<>();
            detailsList = recursionRetreat(detailsList,ids, commodityId, specsId, num);
            if (!CollectionUtils.isEmpty(detailsList)){

                for(SysStoreReplenishDetails replenishDetails : detailsList){
                    if (replenishDetails.getIsStatis() == 1){
                        retreatNum = retreatNum + replenishDetails.getHaveStock();
                    }
                }
            }
        }
        //修改库存
        Long countNum = stock.getNum() + num;
        Long expiredNum = stock.getExpiredNum() + retreatNum;//加回过期商品总数量
        sysStoreStockMapper.updateStorkNumBySpecsId(storeId,specsId,commodityId,countNum,expiredNum);
        return ResponseData.success();
    }

    private List<SysStoreReplenishDetails> recursionRetreat(List<SysStoreReplenishDetails> detailsList,List<Long> ids,Long commodityId,Long specsId,Long num){
        //查询剩余数量小于补货数量的记录
        SysStoreReplenishDetails details = sysStoreReplenishDetailsMapper.selectRetreat(ids,commodityId,specsId);
        if (ObjectUtils.isEmpty(details)){
            return null;
        }
        long detNum = details.getHaveStock() + num;
        if (detNum <= details.getNum()){
            sysStoreReplenishDetailsMapper.updateNum(details.getId(),detNum);
            details.setHaveStock(num);//变更数量暂放HaveStock字段 返回计算用
            detailsList.add(details);
            return detailsList;
        }else {
            sysStoreReplenishDetailsMapper.updateNum(details.getId(),details.getNum());
            details.setHaveStock(details.getNum() - details.getHaveStock());//本条记录 变更数量暂放HaveStock字段 返回计算用
            detailsList.add(details);
            recursionRetreat(detailsList,ids,commodityId,specsId,detNum - details.getNum());
        }
        return detailsList;
    }

    @Override
    public ResponseData delStock(Long id) {
        SysStoreStock stock = sysStoreStockMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(stock)){
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        if (stock.getNum() > 0){
            return ResponseData.fail("库存中存在此商品");
        }
        sysStoreStockMapper.updateDel(id);
        return ResponseData.success();
    }

    @Override
    public SysStoreStock selectByPrimaryKey(Long id) {
        return sysStoreStockMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateStockNum(Long id, Long num) {
        return sysStoreStockMapper.updateStorkNumById(id,num);
    }

    @Override
    public List<SysStoreStorkRemindResp> storeStorkExceedAll() {
        SysSystemParam systemParam = sysSystemParamMapper.selectValueByKey(SystemParamsEnum.BATTERY_TIME_OUT.getValue());
        if (ObjectUtils.isEmpty(systemParam)){
            return null;
        }
        return sysStoreReplenishDetailsMapper.selectTimeOutAll(systemParam.getParamValue());
    }

    @Override
    public List<SysStoreStorkRemindResp> storeStorkAgentLoginId() {
        SysSystemParam systemParam = sysSystemParamMapper.selectValueByKey(SystemParamsEnum.BATTERY_TIME_OUT.getValue());
        if (ObjectUtils.isEmpty(systemParam)){
            return null;
        }
        return sysStoreReplenishDetailsMapper.selectTimeOutAgent(systemParam.getParamValue());
    }

//    @Override
//    public int updateRemind(Long id) {
//        return sysStoreReplenishDetailsMapper.updateRemind(id);
//    }

    @Override
    public ResponseData<List<SysStoreStorkDetailsAppResp>> timeOutStockInfo(Long storeId) {
        return ResponseData.success(sysStoreReplenishDetailsMapper.timeOutStockInfo(storeId));
    }

    @Override
    public SysStoreLoginInfo storeLoginInfo(Long loginInfoId) {
        return sysStoreLoginInfoMapper.selectByStoreInfoId(loginInfoId);
    }

    @Override
    public ResponseData<List<SysStorkDetailsTimeOutResp>> timeOutStock(Long loginInfoId) {
        SysStoreLoginInfo info = sysStoreLoginInfoMapper.selectByStoreInfoId(loginInfoId);
        if (ObjectUtils.isEmpty(info)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        SysSystemParam systemParam = sysSystemParamMapper.selectValueByKey(SystemParamsEnum.BATTERY_TIME_OUT.getValue());
        if (ObjectUtils.isEmpty(systemParam)){
            return ResponseData.fail("系统配置未找到");
        }
        return ResponseData.success(sysStoreReplenishMapper.selectTimeOut(info.getStoreId(),systemParam.getParamValue()));
    }

    @Override
    public ResponseData<List<SysStoreStorkDetailsAppResp>> timeOutDetails(Long storeId) {

        List<SysStoreStorkDetailsAppResp> list = sysStoreStockMapper.selectList(storeId);

        return ResponseData.success(list);
    }

    @Override
    public Long findStoreCurrentStock(Long storeId) {
        return sysStoreStockMapper.findStoreCurrentStock(storeId);
    }

    @Override
    public Long findConfirmStock(Long storeId) {
        return sysStoreReplenishMapper.findConfirmStock(storeId);
    }

    @Override
    public void outTimeStatis() {

        SysSystemParam systemParam = sysSystemParamMapper.selectValueByKey(SystemParamsEnum.BATTERY_TIME_OUT.getValue());
        if (ObjectUtils.isEmpty(systemParam)){
            log.error("系统配置商品过期时间未找到");
        }
        //查询过期补货详情
         List<SysStoreReplenishDetails> list = sysStoreReplenishDetailsMapper.statisExpireNum(systemParam.getParamValue());
        for (SysStoreReplenishDetails details : list){
            if (details.getHaveStock() > 0){
                SysStoreReplenish sysStoreReplenish = sysStoreReplenishMapper.selectByPrimaryKey(details.getReplenishId());
                if (!ObjectUtils.isEmpty(sysStoreReplenish)){
                    //查询库存
                    SysStoreStock storeStock = sysStoreStockMapper.selectBySpecsId(sysStoreReplenish.getStoreId(), details.getCommoditySpecsId());
                    if (!ObjectUtils.isEmpty(storeStock)){
                        SysStoreStock sysStoreStock = new SysStoreStock();
                        sysStoreStock.setId(storeStock.getId());
                        sysStoreStock.setExpiredNum(storeStock.getExpiredNum() + details.getHaveStock());
                        sysStoreStock.setUpdatedAt(new Date());
                        sysStoreStockMapper.updateByPrimaryKeySelective(sysStoreStock);
                    }
                }
            }
        }
        sysStoreReplenishDetailsMapper.updateIsStatis(systemParam.getParamValue());

    }

    @Override
    public Long findExpiredNum(Long stockId) {
        SysStoreStock sysStoreStockInfo = sysStoreStockMapper.selectByPrimaryKey(stockId);
        return sysStoreStockInfo.getExpiredNum();
    }

    @Override
    public List<Long> selectCommoditySpecsIdByStoreId(Long storeId) {
        return sysStoreStockMapper.selectCommoditySpecsIdByStoreId(storeId);
    }
}
